<template>
  <div class="app-container">
    <el-row style="margin-bottom: 10px" :gutter="8">
      <el-col :xs="{span: 24}" :sm="{span: 24}" :md="{span: 24}" :lg="{span: 12}" :xl="{span: 12}">
        <el-button class="pan-btn success-btn" v-if="isReregist" @click="submit" icon="el-icon-s-promotion" style="float: right;" type="success" size="mini">
          {{ isUpdate ? '重新发送' : ('发送至' + fromUserName) }}
        </el-button>
        <el-button class="pan-btn success-btn" v-if="sendAndGetBtn" @click="submit" icon="el-icon-s-promotion" style="float: right;" type="success" size="mini">
          发送并取样
        </el-button>
        <el-button class="pan-btn success-btn" v-if="sendBtn && !sendAndGetBtn" @click="submit" icon="el-icon-s-promotion" style="float: right;" type="success" size="mini">
          发送
        </el-button>
        <el-tooltip effect="dark" :content="isFullLast ? '不填充' : '自动填充'" placement="top">
          <el-switch
            :disabled="fullLastDisabled"
            style="float: right;
            margin-right: 40px;
            margin-top: 8px;"
            v-model="isFullLast"
            @change="changeFullLast"
            active-color="#7cbd36"
            inactive-color="#ff4949"
            inactive-text="上一单">
          </el-switch>
        </el-tooltip>
      </el-col>
    </el-row>

    <el-row :gutter="8">
      <el-col :xs="{span: 24}" :sm="{span: 24}" :md="{span: 24}" :lg="{span: 12}" :xl="{span: 12}">
        <el-card shadow="hover" class="card">
          <el-form label-width="80px">
            <el-form-item label="品名:">
              <span slot="label">品&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;名:</span>
              <el-form v-if="product != ''" :inline="true">
                <el-form-item>
                  {{product.productName}}
                </el-form-item>
                <el-form-item label="物料编码:">
                  {{product.productGmp}}
                </el-form-item>
                <el-form-item label="货品规格:" v-if="product.productSpec && product.productSpec != null">
                  <span v-html="product.productSpec"></span>
                </el-form-item>
                <el-form-item>
                  <el-button
                    :disabled="isReregist"
                    type="info"
                    class="pan-btn info-btn"
                    @click="showProductSelect"
                    size="mini">
                    重新选择
                  </el-button>
                </el-form-item>
              </el-form>
              <el-button
                v-if="product == ''"
                type="info"
                class="pan-btn info-btn"
                @click="showProductSelect"
                size="mini">
                请选择
              </el-button>
            </el-form-item>

            <el-form-item label="取样车间:">
              <el-select id="workshop" v-model="dataForm.workshop" value-key="workshopId" @change="setWorkshop" filterable placeholder="取样车间" style="width: 100%;" size="small">
                <el-option
                  v-for="item in workshopList"
                  :key="item.workshopId"
                  :label="item.workshopName"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="批号:">
              <span slot="label">批&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;号:</span>
              <span v-if="product != ''">{{ product.productGmp + ' -' }}</span>
              <span v-if="dataForm.workshop != ''">{{ dataForm.workshop.workshopCode + ' -' }}</span>
              <el-input id="batchNum" v-model="checkList.batchNum" @change="setBatchNum" placeholder="批号" size="small" :style="{'width': comptBatchWid }" />
            </el-form-item>

            <el-form-item label="取样容器:">
              <el-radio-group v-model="dataForm.packContainerId" @change="setPackContainer" size="small">
                <el-radio-button v-for="item in packContainerList" :key="item.packContainerId" :label="item.packContainerId">{{ item.packContainerName }}</el-radio-button>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="样品量:">
              <span slot="label">样&nbsp;&nbsp;品&nbsp;&nbsp;量:</span>
              {{ dataForm.waterGets.length + ' 个' }}
            </el-form-item>

            <el-form-item label="取样点:">
              <span slot="label">取&nbsp;&nbsp;样&nbsp;&nbsp;点:</span>
              <div v-if="waterGetList.length > 0 && product != '' && dataForm.workshop != ''">
                <span>{{ product.productGmp + ' -' }}</span>
                <span>{{ dataForm.workshop.workshopCode + ' -' }}</span>
                <el-select v-if="product.productName != '饮用水'" id="waterGets" v-model="dataForm.waterGets" value-key="waterGetId" multiple @change="setWaterGet" @remove-tag="removeWaterGet" filterable placeholder="取样点" :style="{'width': comptBatchWid }" size="small">
                  <el-option
                    v-for="wg in waterGetList"
                    :key="wg.waterGetId"
                    :label="wg.waterGetName"
                    :value="wg">
                  </el-option>
                </el-select>
                <el-select v-else id="waterGets" v-model="dataForm.waterGets[0]" value-key="waterGetId" filterable placeholder="取样点" :style="{'width': comptBatchWid }" size="small">
                  <el-option
                    v-for="wg in waterGetList"
                    :key="wg.waterGetId"
                    :label="wg.waterGetName"
                    :value="wg">
                  </el-option>
                </el-select>
              </div>
              <span v-else style="color: #F56C6C">请先选择货品并配置此车间的取样点</span>
            </el-form-item>

            <el-form-item label="请检项目:" v-if="product != ''">
              <div v-if="allItems.length == 0" style="color: #F56C6C;">请添加此货品的检验标准</div>
              <div v-else>
                <el-radio-group :disabled="true" v-model="checkList.isAllTest" @change="changeItems" size="small">
                  <el-radio-button :label="0">全检</el-radio-button>
                  <el-radio-button :label="1">其他</el-radio-button>
                </el-radio-group>
                <el-button
                  style="margin-left: 20px;"
                  class="pan-btn info-btn"
                  type="info"
                  @click="showStandardDrawer"
                  size="mini">
                  查看项目
                </el-button>
              </div>
            </el-form-item>

            <el-form-item label="请验目的:">
              <el-radio-group v-model="dataForm.checkPurposeId" @change="setCheckPurpose" size="small">
                <el-radio-button v-for="item in checkPurposeList" :key="item.checkPurposeId" :label="item.checkPurposeId">{{item.checkPurposeName}}</el-radio-button>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="请验日期:">
              <el-date-picker
                id="registCheckDate"
                v-model="checkList.registCheckDate"
                @change="setGetDate"
                align="right"
                type="date"
                placeholder="选择日期"
                :picker-options="pickerOptions"
                style="width: 100%;"
                format="yyyy 年 MM 月 dd 日"
                value-format="yyyy-MM-dd HH:mm:ss"
                size="small">
              </el-date-picker>
            </el-form-item>

            <el-form-item label="请验部门:">
              {{ checkList.registCheckDepartmentName }}
            </el-form-item>

            <el-form-item label="请验人:">
              <span slot="label">请&nbsp;&nbsp;验&nbsp;&nbsp;人:</span>
              {{checkList.registCheckUserName}}
            </el-form-item>

            <el-form-item label="取样日期:">
              <el-date-picker
                id="getDate"
                v-model="checkList.getDate"
                align="right"
                type="date"
                placeholder="选择日期"
                :picker-options="pickerOptions"
                style="width: 100%;"
                format="yyyy 年 MM 月 dd 日"
                value-format="yyyy-MM-dd HH:mm:ss"
                size="small">
              </el-date-picker>
            </el-form-item>

            <el-form-item label="取样人:">
              <span slot="label">取&nbsp;&nbsp;样&nbsp;&nbsp;人:</span>
              {{checkList.getUserName}}
            </el-form-item>

            <el-form-item>
              <span slot="label">备&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;注:</span>
              <el-input v-model="checkList.remark" placeholder="备注" size="small"/>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>

      <el-col :xs="{span: 24}" :sm="{span: 24}" :md="{span: 24}" :lg="{span: 12}" :xl="{span: 12}">
        <el-table
          :data="dataForm.waterGets.filter(wg => {return wg.waterGetId != 0})"
          border
          fit
          highlight-current-row
          style="width: 100%">
            <el-table-column
            	type="index"
            	header-align="center"
            	align="center"
            	label="序号"
              width="50">
            </el-table-column>
            <el-table-column
              prop="waterGetName"
            	header-align="center"
            	align="center"
            	label="取样点"
              width="80">
            </el-table-column>
            <el-table-column
              v-for="(wq,wqIndex) in waterQuantityList"
              :key="wqIndex"
              :label="wq.waterQuantityName">
              <el-table-column
              header-align="center"
              align="center">
                <template slot="header" slot-scope="scope">
                  <el-input v-model="wq.allQ" @change="setAllWaterQuantity(wqIndex)" :clearable="true" size="mini">
                    <template slot="append">{{ qtUnit.unitName }}</template>
                  </el-input>
                </template>
                <template slot-scope="scope">
                  <el-input v-model="scope.row.cgyqs[wqIndex].waterQuantity" @change="setWaterQuantity(scope.$index, wqIndex)" :clearable="true" size="mini">
                    <template slot="append">{{ qtUnit.unitName }}</template>
                  </el-input>
                </template>
              </el-table-column>
            </el-table-column>
        </el-table>
      </el-col>
    </el-row>

    <product-select
      v-if="productSelectVisible"
      @getProduct="getProduct"
      @showProductSelect="colseInner('productSelectVisible')"
      :childDataForm="childDataForm" />

    <standard-drawer
      v-if="standardDrawerVisible"
      @getStandard="getStandard"
      @close="colseInner('standardDrawerVisible')"
      :childDataForm="childDataForm"/>

  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import { CODE_OK } from '@/common/js/config'
  import { isBlank,unique,arrEq } from '@/common/js/utils'
  import { isPositiveIntegerNumber,isPure8Number } from '@/common/js/validate'
  import ProductSelect from '@/views/modules/base/product-select'
  import StandardDrawer from '@/views/modules/base/standard-drawer'
  import {
    getUnitList,
    getPackContainerList,
    getCheckPurposeList,
    getWorkshopList,
    getWaterQuantityList,
    registCheck,
    getLastCheckForRegist,
    getRegistCheckInfo,
    checkBatchNum
  } from '@/api/check'
  import { getWaterGetListByWorkshopId } from "@/api/workshop"
  import { getStandardByProductId } from '@/api/standard'
  import Calc from 'calculatorjs'
  export default {
    name: 'registcheck703',
    components: {
    	ProductSelect,StandardDrawer
    },
    data() {
      return {
        printCheckVersion: '03',
        isReregist: false,
        isUpdate: false,
        isFullLast: false,
        fromUserName: null,
        fromStatus: null,
        checkReturnId: null,
        product: '',
        productSelectVisible: false,
        standardDrawerVisible: false,
        standard: '',
        allItems: [],
        items: [],
        unitList: [],
        qtUnit: '',
        workshopList: [],
        waterGetList: [],
        waterQuantityList: [],
        packContainerList: [],
        checkPurposeList: [],
        dataForm: {
          packContainerId: '',
          checkPurposeId: '',
          workshop: '',
          waterGets: [],
          selectWqs: []
        },
        oldOptions: [],
        checkList: {
          checkTypeId: 7,
          checkTypeName: '制药用水/纯蒸汽',
          isTest: 0,
          isAllTest: '',
          isMerge: 1,
          status: 1
        },
        ysList: {},
        childDataForm: '',
        crys: []
      }
    },
    created() {
      if (!isBlank(this.$route.query.checkId)) {
        this.isReregist = true
      }
      this.init()
    },
    computed: {
      ...mapGetters([
         'userInfo'
      ]),
      fullLastDisabled() {
        return this.allItems.length == 0 || this.product == '' || isBlank(this.dataForm.workshop.workshopId) || this.isReregist
      },
      sendBtn() {
        return !this.isReregist && !this.isUpdate && this.userInfo.roles.filter(r => {return r.roleName == '请验'}).length > 0
      },
      sendAndGetBtn() {
        return !this.isReregist && !this.isUpdate && (this.userInfo.roles.filter(r => {return r.roleName == '取样' || r.roleName == '信息' || r.roleName == '请取样'}).length > 0 || this.userInfo.userId == 1)
      },
      comptBatchWid() {
        if (this.product == '' && this.dataForm.workshop == '') {
          return '100%'
        }else if(this.product != '' && this.dataForm.workshop == '') {
          return '95%'
        }else if(this.product != '' && this.dataForm.workshop != '') {
          return '92%'
        }else{
          return '96%'
        }
      }
    },
    methods: {
      init() {
        this.getInfo()
        this.setRegistInfo()
        if (this.isReregist) {
          const params = {
            checkId: this.$route.query.checkId,
            content: 'ys'
          }
          getRegistCheckInfo(params).then(res => {
            if (res.code === CODE_OK) {
              this.fillData(res.info)
              this.setReregistInfo()
            }else{
              this.$message({
                message: res.msg,
                type: 'error',
                duration: 1500,
                onClose: () => {
                  window.history.go(-1)
                }
              })
            }
          })
        }else{
          this.setRegistInfo()
        }
      },
      fillData(info) {
        let checkList = info.checkList
        let ysList = info.ysList
        this.checkList = JSON.parse(JSON.stringify(checkList))
        this.ysList = JSON.parse(JSON.stringify(ysList))
        this.dataForm.packContainerId = ysList.packContainerId
        this.dataForm.checkPurposeId = ysList.checkPurposeId
        this.dataForm.workshop = {
          workshopId: ysList.workshopId,
          workshopName: ysList.workshopName,
          workshopCode: ysList.workshopCode
        }
        this.setWorkshop()
        if(this.waterQuantityList.length == 0) {
          this.fillData(info)
          return
        }
        this.dataForm.waterGets = info.checkGetYss.map(v => {
          let cgyqs = JSON.parse(JSON.stringify(v.cgyqs))
          //cgyq必须对应wq
          if (cgyqs.length != this.waterQuantityList.length) {
            v.cgyqs = []
            for (let wq of this.waterQuantityList) {
              let newWq = JSON.parse(JSON.stringify(wq))
              for (let cgyq of cgyqs) {
                if (wq.waterQuantityId == cgyq.waterQuantityId) {
                  newWq = JSON.parse(JSON.stringify(cgyq))
                  //此方法是统计已经选择的去重后的wq，也就是已经有取样量的 种类
                  this.selectWqsPush(newWq)
                  break
                }
              }
              v.cgyqs.push(newWq)
            }
          }
          return v
        })
        if (this.isReregist) {
          let barr = this.checkList.batchNum.split('-')
          this.checkList.batchNum = barr[barr.length - 1]
          this.getProduct(info.product)
          this.standard = info.standard
        }
        if (this.isFullLast && this.standard.insideInspectionStandardId != info.standard.insideInspectionStandardId) {
          if (checkList.isAllTest == 0) {
            this.checkList.isAllTest = checkList.isAllTest
            this.items = JSON.parse(JSON.stringify(this.allItems))
          }else{
            this.$message.error("标准已升级，请自己选择检验项目")
          }
        }else{
          this.checkList.isAllTest = checkList.isAllTest
          this.items = info.items
        }
      },
      setReregistInfo() {
        if (this.$route.query.checkReturnId != 0) {
          this.fromUserName = this.$route.query.fromUserName
          this.fromStatus = this.$route.query.fromStatus
          this.checkReturnId = this.$route.query.checkReturnId
        }else{
          this.isUpdate = true
        }
      },
      setRegistInfo() {
        this.checkList.registCheckDepartmentId = this.userInfo.departmentId
        this.checkList.registCheckDepartmentName = this.userInfo.departmentName
        this.checkList.registCheckUserId = this.userInfo.userId
        this.checkList.registCheckUserName = this.userInfo.name
        if (this.sendAndGetBtn) {
          this.checkList.getUserId = this.userInfo.userId
          this.checkList.getUserName = this.userInfo.name
        }
      },
      getInfo() {
        const params = {
          checkTypeId: 7,
          printVersion: this.printCheckVersion
        }
        getUnitList().then(res => {
          if (res.code === CODE_OK) {
            this.unitList = res.list
            this.qtUnit = this.unitList.find(u => u.unitName == 'ml')
          }else{
            this.$message.error(res.msg)
          }
        })
        getPackContainerList(params).then(res => {
          if (res.code === CODE_OK) {
            this.packContainerList = res.list
          }else{
            this.$message.error(res.msg)
          }
        })
        getCheckPurposeList(params).then(res => {
          if (res.code === CODE_OK) {
            this.checkPurposeList = res.list
          }else{
            this.$message.error(res.msg)
          }
        })
        getWorkshopList().then(res => {
          if (res.code === CODE_OK) {
            this.workshopList = res.list
          }else{
            this.$message.error(res.msg)
          }
        })
        getWaterQuantityList().then(res => {
          if (res.code === CODE_OK) {
            this.waterQuantityList = res.list.map((v,i) => {
              this.$set(v,'allQ',null)
              return v
            })
          }else{
            this.$message.error(res.msg)
          }
        })
      },
      showProductSelect() {
        this.childDataForm = {
          checkTypeId: this.checkList.checkTypeId
        }
        this.productSelectVisible = true
      },
      changeFullLast() {
        if (this.isFullLast) {
          const params = {
            content: 'ys',
            productId: this.product.productId,
            workshopId: this.dataForm.workshop.workshopId
          }
          getLastCheckForRegist(params).then(res => {
            if (res.code === CODE_OK) {
              this.fillData(res.info)
              this.setRegistInfo()
            }else{
              this.$message.error(res.msg)
              this.isFullLast = false
            }
          })
        }else{
          //初始化

        }
      },
      submit() {
        this.checkList.printCheckVersion = this.printCheckVersion
        //先表单验证，后整理
        if (this.formVerify()) {
          const data = this.neatenData()
          registCheck(data).then(res => {
            if (res.code === CODE_OK) {
              this.$message({
                message: '提交成功',
                type: 'success',
                duration: 1000,
                onClose: () => {
                 window.history.go(-1)
                }
              })
            }else{
              this.$message.error(res.msg)
            }
          })
        }
      },
      neatenData() {
        let commonStr = this.product.productGmp + '-' + this.dataForm.workshop.workshopCode + '-'
        //check_list
        let checkList = JSON.parse(JSON.stringify(this.checkList))
        //批号
        checkList.batchNum = commonStr + checkList.batchNum
        checkList.batchNumPrefix = checkList.batchNum
        //check_get_ys and check_get_ys_quantity
        let allGetQuantity = 0
        let wgs = JSON.parse(JSON.stringify(this.dataForm.waterGets.filter(wg => {return wg.waterGetId != 0})))
        for (let wg of wgs) {
          for (let j in this.waterQuantityList) {
            if (!isBlank(wg.cgyqs[j].waterQuantity)) {
              allGetQuantity = Calc.add(allGetQuantity, wg.cgyqs[j].waterQuantity)
            }
          }
        }
        //check_get -> check_list
        checkList.getQuantity = allGetQuantity
        checkList.getUnitId = this.qtUnit.unitId
        checkList.getUnitName = this.qtUnit.unitName
        let wgs2 = JSON.parse(JSON.stringify(wgs))
        wgs2 = wgs.map(wg => {
          wg.ysGetId = null
          wg.cgyqs = wg.cgyqs.filter(v => {
            return !isBlank(v.waterQuantity)
          })
          return wg
        })
        //如果为退回后发起并已经收样，则需要重构收样
        let crys = []
        if (this.isReregist) {
          if (parseInt(this.$route.query.fromStatus) > 2) {
            for (let wg of wgs) {
              let wqArr = wg.cgyqs
              for (let wq of wqArr) {
                let cry = JSON.parse(JSON.stringify(wq))
                this.$set(cry,'reCount',1)
                if (crys.length == 0) {
                  crys.push(cry)
                }else{
                  for (let i=0,j=crys.length; i<j; i++) {
                    //若id和取样量都相同则放入同一组
                    if (crys[i].waterQuantityId == cry.waterQuantityId && crys[i].waterQuantity == cry.waterQuantity) {
                      cry = JSON.parse(JSON.stringify(crys[i]))
                      cry.reCount++
                      crys[i] = cry
                      break
                    }
                    if (i==j-1) {
                      crys.push(cry)
                    }
                  }
                }
              }
            }
          }
        }
        const data = {
          rag: true,
          content: 'ys',
          checkList: checkList,
          ysList: this.ysList,
          product: this.product,
          standard: this.standard,
          items: this.items,
          checkGetYss: wgs,
          fromStatus: this.fromStatus,
          checkReturnId: this.checkReturnId,
          crys: crys.length > 0 ? crys : null
        }
        return data
      },
      formVerify() {
        //选择货品
        if (isBlank(this.product)) {
          this.$message.error('请选择货品')
          return false
        }
        //选择车间
        if (isBlank(this.dataForm.workshop)) {
          this.$message.error('请选择取样车间')
          $("#workshop").css({"border-color" : "#D08585"})
          return false
        }
        $("#workshop").removeAttr('style')
        //输入批号
        if (isBlank(this.checkList.batchNum)) {
          this.$message.error('请输入批号')
          $("#batchNum").css({"border-color" : "#D08585"})
          return false
        }
        $("#batchNum").removeAttr('style')
        //选择取样容器
        if (isBlank(this.dataForm.packContainerId)) {
          this.$message.error('请选择取样容器')
          return false
        }
        //选择取样点
        if (!this.dataForm.waterGets.length > 0) {
          this.$message.error('请选择取样点')
          $("#waterGets").css({"border-color" : "#D08585"})
          return false
        }
        //表格中
        let wgs = this.dataForm.waterGets.filter(v => {return v.waterGetId != 0})
        for (let wg of wgs) {
          let isAllBlank = true
          for (let wqIndex in this.waterQuantityList) {
            if (!isBlank(wg.cgyqs[wqIndex].waterQuantity)) {
              isAllBlank = false
            }
          }
          if (isAllBlank) {
            this.$message.error('取样点'+wg.waterGetName+'所有取样量不能都为空')
            return false
          }
        }
        //选择请检项目
        if (this.items.length == 0) {
          this.$message.error('请选择请验项目')
          return false
        }
        //检验项目中的小组集合a == 检验类别中的小组集合b (小组相同)
        if (!this.groupOk()) {
          return false
        }
        //选择请验目的
        if (isBlank(this.dataForm.checkPurposeId)) {
          this.$message.error('请选择请验目的')
          return false
        }
        //选择请验日期
        if (isBlank(this.checkList.registCheckDate)) {
          this.$message.error('请选择请检日期')
          $("#registCheckDate").css({"border-color" : "#D08585"})
          return false
        }
        $("#registCheckDate").removeAttr('style')
        //选择取样日期
        if (isBlank(this.checkList.getDate)) {
          this.$message.error('请选择取样日期')
          $("#getDate").css({"border-color" : "#D08585"})
          return false
        }
        $("#getDate").removeAttr('style')
        //userInfo
        if (isBlank(this.checkList.registCheckDepartmentId) || isBlank(this.checkList.registCheckUserId)) {
          this.$message.error('登录过期,请刷新页面')
          return false
        }
        return true
      },
      groupOk() {
        //取检验项目中的小组，取检验类别中的小组，比较
        let itemGroupIds = unique(this.items.map(v => {return v.inspectionGroupId}))
        let wqGroupIds = unique(this.dataForm.selectWqs.map(v => {return v.inspectionGroupId}))
        if (!arrEq(itemGroupIds, wqGroupIds)) {
          let itemGroupNames = unique(this.items.map(v => {return v.inspectionGroupName}))
          let wqGroupNames = unique(this.dataForm.selectWqs.map(v => {return v.inspectionGroupName}))
          let msg = '检验项目中的小组有:' + itemGroupNames + ',检验类别中的小组有:' + wqGroupNames + ',请联系标准管理员(刘威)验证检验项目所属小组是否正确。'
          this.$message({
            message: msg,
            type: 'error',
            duration: 3500
          })
          return false
        }
        return true
      },
      getProduct(p) {
        this.product = p
        if (this.waterGetList.length != 0 && this.product.productName == '饮用水') {
          this.waterGetList = this.waterGetList.filter(wg => {
            return wg.waterGetId != 0
          })
        }
        const params = {
          productId: p.productId
        }
        this.initStandard()
        getStandardByProductId(params).then(res => {
          if (res.code === CODE_OK) {
            this.allItems = res.standard.items
            if (this.allItems.length == 0) return
            if (!this.isReregist) {
              this.checkList.isAllTest = null
              this.items = []
              let ati = res.standard.accordingToInside
              //如果是注射用水，那么就裁剪检验依据
              let filstr = '注射用水'
              if (p.productName.trim() == filstr) {
                let snArr = ati.split('、')
                for (let s of snArr) {
                  if (s.indexOf(filstr) > -1 && s.indexOf(res.standard.insideInspectionStandardNum) > -1) {
                    ati = s
                    break
                  }
                }
              }
              this.standard = {
                insideInspectionStandardId: res.standard.insideInspectionStandardId,
                insideInspectionStandardNum: res.standard.insideInspectionStandardNum,
                nationInspectionStandardNum: res.standard.nationInspectionStandardNum,
                accordingToInside: ati,
                accordingToNation: res.standard.accordingToNation
              }
            }
          }else{
            this.$message.error(res.msg)
          }
        })
        this.checkBatchNum()
      },
      getStandard(standardObj) {
        this.$message.info("无法更改项目，因为项目绑定了检验类别")
      },
      initStandard() {
        this.standard = ''
        this.allItems = []
        this.items = []
        this.checkList.isAllTest = ''
      },
      changeItems() {
        if (this.checkList.isAllTest == 0) {
          this.items = JSON.parse(JSON.stringify(this.allItems))
        }else{
          this.items = []
          this.showStandardDrawer()
        }
      },
      showStandardDrawer() {
        this.childDataForm = {
          product: this.product,
          standard: this.standard,
          allItems: this.allItems,
          checkedItems: this.items
        }
        this.standardDrawerVisible = true
      },
      colseInner(val) {
        this.childDataForm = ''
        this[val] = false
      },
      //set
      setWaterGet(nowArr) {
        let allArr = JSON.parse(JSON.stringify(this.waterGetList))
        let selectArr = JSON.parse(JSON.stringify(nowArr))
        //取出上一次的值，进行判断
        let oldArr = this.oldOptions.length === 1 ? this.oldOptions[0] : []
        //取判断值
        let nowAllSelect = nowArr.filter(a => {return a.waterGetId === 0}).length === 1
        let oldAllSelect = oldArr.filter(a => {return a.waterGetId === 0}).length === 1
        //此次全选
        if (nowAllSelect) {
          //上次全选，代表取消了除全选外的任一个选项
          if (oldAllSelect) {
            //取消全选标志
            nowArr = nowArr.filter(a => {return a.waterGetId !== 0})
            selectArr = nowArr
          }else{
            //上次未全选，代表全选
            selectArr = allArr
          }
        }else{
          //此次未全选
          //上次全选,代表取消全选
          if (oldAllSelect) {
            selectArr = []
          }else{
            //上次未全选，代表普通操作
            //若选择上所有选项，则添加全选标志
            if (nowArr.length === allArr.length - 1) {
              selectArr = allArr
            }else{
              //若全程全选未参与
              if (nowArr.length === 2 && oldArr.length === 1) {
                //模拟滑动选择
                //寻找第一、二个元素的位置，进行中间截取
                let oneIndex = allArr.findIndex(a => a.waterGetId === nowArr[0].waterGetId)
                let twoIndex = allArr.findIndex(a => a.waterGetId === nowArr[1].waterGetId)
                if (oneIndex < twoIndex - 1) {
                  selectArr = allArr.slice(oneIndex, twoIndex + 1)
                  if (selectArr.length === allArr.length - 1) {
                    selectArr = allArr
                  }
                }
              }
            }
          }
        }
        this.dataForm.waterGets = selectArr
        // 储存当前最后的结果 作为下次的老数据
        this.oldOptions[0] = selectArr
      },
      removeWaterGet(wg) {
        this.flushSelectWqs()
      },
      flushSelectWqs() {
        let selectIds = []
        for (let wg of this.dataForm.waterGets) {
          for (let wq of wg.cgyqs) {
            if (isPositiveIntegerNumber(wq.waterQuantity) && selectIds.indexOf(wq.waterQuantityId) == -1) {
              selectIds.push(wq.waterQuantityId)
            }
          }
        }
        this.dataForm.selectWqs = []
        for (let id of selectIds) {
          for (let wq of this.waterQuantityList) {
            if (wq.waterQuantityId == id) {
              this.selectWqsPush(JSON.parse(JSON.stringify(wq)))
            }
          }
        }
      },
      setAllWaterQuantity(j) {
        let wq = this.waterQuantityList[j]
        if (!isPositiveIntegerNumber(wq.allQ)) {
          this.$message.error('取样量为正整数')
          this.waterQuantityList[j].allQ = null
          return
        }
        if (this.selectWqsPush(wq)) {
          this.dataForm.waterGets = this.dataForm.waterGets.map(wg => {
            if (wg.waterGetId != 0) {
              wg.cgyqs[j].waterQuantity = wq.allQ
            }
            return wg
          })
        }else{
          this.waterQuantityList[j].allQ = null
        }
      },
      setWaterQuantity(i,j) {
        let nowAllSelect = this.dataForm.waterGets.filter(a => {return a.waterGetId === 0}).length === 1
        if (nowAllSelect) i = i + 1
        if (!isPositiveIntegerNumber(this.dataForm.waterGets[i].cgyqs[j].waterQuantity)) {
          this.$message.error('取样量为正整数')
          this.dataForm.waterGets[i].cgyqs[j].waterQuantity = null
          return
        }
        this.dataForm.waterGets[i].cgyqs[j].waterQuantity = this.dataForm.waterGets[i].cgyqs[j].waterQuantity * 1
        if (!this.selectWqsPush(this.waterQuantityList[j])) {
          this.dataForm.waterGets[i].cgyqs[j].waterQuantity = null
        }
      },
      selectWqsPush(wq) {
        if (typeof(this.dataForm.selectWqs.find(s => s.waterQuantityId == wq.waterQuantityId)) != 'object') {
          this.dataForm.selectWqs.push(wq)
        }
        if (!this.flushItemsByWq()) {
          this.dataForm.selectWqs.pop()
          return false
        }
        return true
      },
      flushItemsByWq() {
        if (!this.flushItemsByWqVerify()) {
          return false
        }
        let wqIds = this.dataForm.selectWqs.map(w => {return w.waterQuantityId})
        this.items = this.allItems.filter(v => {
          return wqIds.indexOf(v.waterQuantityId) > -1
        })
        this.checkList.isAllTest = this.items.length == this.allItems.length ? 0 : 1
        return true
      },
      flushItemsByWqVerify() {
        for (let wq of this.dataForm.selectWqs) {
          if (this.allItems.findIndex(v => v.waterQuantityId == wq.waterQuantityId) == -1) {
            this.$message.error('所有项目中不包含此检验类别，请重新检查')
            return false
          }
        }
        return true
      },
      setWorkshop() {
        this.ysList.workshopId = this.dataForm.workshop.workshopId
        this.ysList.workshopName = this.dataForm.workshop.workshopName
        this.ysList.workshopCode = this.dataForm.workshop.workshopCode
        const params = {
        	page: 1,
          limit: 9999,
          workshopId: this.ysList.workshopId
        }
        getWaterGetListByWorkshopId(params).then(res => {
        	if (res.code === CODE_OK) {
        		this.waterGetList = res.page.list.map(v => {
              this.$set(v,'cgyqs',JSON.parse(JSON.stringify(this.waterQuantityList)))
              return v
            })
            if (!isBlank(this.product) && this.waterGetList.length != 0) {
              if (this.product.productName != '饮用水') {
                this.waterGetList.unshift({
                  waterGetId: 0,
                  waterGetName: '全选'
                })
              }
            }
        	}else{
        		this.$message.error(res.msg)
        	}
        })
        this.checkBatchNum()
      },
      setBatchNum() {
        this.checkList.batchNum = this.checkList.batchNum.trim()
        if (!isPure8Number(this.checkList.batchNum)) {
          this.$message.error('批号后面为8位纯数字类型')
          this.checkList.batchNum = null
        }
        this.checkBatchNum()
      },
      //检查是否跨批号
      checkBatchNum() {
        let b,ymd
        if (isPure8Number(ymd = b = this.checkList.batchNum) && !isBlank(this.product.productGmp) && !isBlank(this.dataForm.workshop.workshopCode)) {
          let y = parseInt((ymd = ymd.split("-")[ymd.split("-").length-1]).substring(0,4)),
              m = parseInt(ymd.substring(4,6)),
              d = parseInt(ymd.substring(6)),
              expectedLastBatchNum,
              preBatch = this.product.productGmp + '-' + this.dataForm.workshop.workshopCode + '-',
              mode
          //当前：S3-E-20200101
          //期望：S3-E-201912
          if (m == 1 && d == 1) {
            mode = 'like'
            expectedLastBatchNum = preBatch + (y-1) + 12 + "**"
          }else if(m != 1 && d == 1){
            //当前：S3-E-20200901
            //期望：S3-E-202008
            mode = 'like'
            expectedLastBatchNum = preBatch + y + ((m-1)<10?"0":"") + (m-1) + "**"
          }else{
            //当前：S3-E-20200923
            //期望：S3-E-20200922
            mode = 'eq'
            expectedLastBatchNum = preBatch + y + (m<10?"0":"") + m + ((d-1)<10?"0":"") + (d-1)
          }
          const params = {
            mode: mode,
            checkTypeId: this.checkList.checkTypeId,
            batchNum: expectedLastBatchNum
          }
          checkBatchNum(params).then(res => {
            if (res.code === CODE_OK) {
              if (res.reCount == 0) {
                this.$confirm('不存在批次'+expectedLastBatchNum+',确定是否跨批号发起？', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                }).then(() => {}).catch(() => {
                  this.checkList.batchNum = null
                  this.$message.error('请重新输入批号')
                })
              }
            }else{
              this.$message.error(res.msg)
            }
          })
        }
      },
      setPackContainer() {
        let id = this.dataForm.packContainerId
        for (let p of this.packContainerList) {
          if (p.packContainerId == id) {
            this.ysList.packContainerId = p.packContainerId
            this.ysList.packContainerName = p.packContainerName
            break
          }
        }
      },
      setCheckPurpose() {
        let id = this.dataForm.checkPurposeId
        for (let c of this.checkPurposeList) {
          if (c.checkPurposeId == id) {
            this.ysList.checkPurposeId = c.checkPurposeId
            this.ysList.checkPurposeName = c.checkPurposeName
            break
          }
        }
      },
      setGetDate() {
        if (isBlank(this.checkList.getDate)) {
          this.$set(this.checkList,'getDate',JSON.parse(JSON.stringify(this.checkList.registCheckDate)))
        }
      }
    }
  }
</script>

<style scoped>
  .el-form-item {
    margin-bottom: 0px !important;
  }
  .el-form-item__content .el-input-group {
    vertical-align: inherit !important;
  }
</style>
